/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ortus.media.metadata;

import ortus.cache.cacheEngine;
import ortus.*;
import java.util.List;
import sagex.api.MediaFileAPI;
import sagex.api.ShowAPI;

/**
 *
 * @author jphipps
 */
public class DBMetadata extends ortus.ortusvars implements IMetadataProvider {
    public long GetOriginalAirDate(Object mediafile) {
        return 0;
    }

    public String GetMediaTitle(Object mediafile) {
	    String mediatitle = cacheEngine.getInstance().GetCache(mediafile).GetMediaTitle();
//	    if ( mediatitle.isEmpty())
//		    mediatitle = MediaFileAPI.GetMediaTitle(mediafile);
	    return  mediatitle;
//            List<Object> result = ortus.api.executeSQLQuery("select showtitle from allmedia where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
//            if ( result.size() > 0) {
//                return (String)result.get(0);
//            } else {
//                return MediaFileAPI.GetMediaTitle(mediafile);
//            }
    }
    public String GetSageMediaTitle(Object smo) {
	    return ortus.cache.cacheEngine.getInstance().GetSageMediaCache(smo).GetMediaTitle();
    }
    public void SetMediaTitle(Object mediafile,String title) {
            ortus.api.executeSQL("update sage.media set mediatitle = '" + title + "' where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
    }

    public String GetShowTitle(Object mediafile) {
	    return cacheEngine.getInstance().GetCache(mediafile).GetMediaTitle();

//            List<Object> result = ortus.api.executeSQLQuery("select showtitle from allmedia where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
//	    if ( result.size() > 0 )
//		return (String)result.get(0);
//	    else
//		return MediaFileAPI.GetMediaTitle(mediafile);
    }

    public String GetEpisodeTitle(Object mediafile) {
//	    return cacheEngine.getInstance().GetCache(mediafile).GetEpisodeTitle();
	    String episodetitle = cacheEngine.getInstance().GetCache(mediafile).GetEpisodeTitle();
	    if ( episodetitle.isEmpty())
		    episodetitle = ShowAPI.GetShowEpisode(mediafile);
	    return  episodetitle;
//            List<Object> result = ortus.api.executeSQLQuery("select episodetitle from allmedia where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
//	    if ( result.size() > 0)
//		return (String)result.get(0);
//	    else
//		return "";
    }
    public String GetSageEpisodeTitle(Object smo) {
	    return ortus.cache.cacheEngine.getInstance().GetSageMediaCache(smo).GetEpisodeTitle();
    }
    public void SetEpisodeTitle(Object mediafile,String title) {
            ortus.api.executeSQL("update sage.media set episodetitle = '" + title + "' where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
    }

    public int GetSeasonNumber(Object mediafile) {
            List<Object> result = ortus.api.executeSQLQueryCache("select seasonno from sage.episode where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
            if ( result.size() > 0)
                return Integer.parseInt((String)result.get(0));
            else
                return 0;
    }

    public int GetEpisodeNumber(Object mediafile) {
            List<Object> result = ortus.api.executeSQLQueryCache("select episodeno from sage.episode where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
            if ( result.size() > 0)
                return Integer.parseInt((String)result.get(0));
            else
                return 0;
    }

    public String GetDescription(Object mediafile) {
	    return cacheEngine.getInstance().GetCache(mediafile).GetDescription();
//            List<Object> result = ortus.api.executeSQLQuery("select description from allmedia where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
//
//            if ( result.size() > 0 && ! ((String)result.get(0)).isEmpty())
//                return (String)result.get(0);
//            else
//                return ShowAPI.GetShowDescription(mediafile);
    }
    public String GetSageDescription(Object smo) {
	    return ortus.cache.cacheEngine.getInstance().GetSageMediaCache(smo).GetDescription();
    }
    public void SetDescription(Object mediafile,String description) {
            int result = ortus.api.executeSQL("update sage.mediavideos set description = '" + description + "' where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
            if ( result < 1) {
                result = ortus.api.executeSQL("insert into sage.mediavideos (mediaid, description) values( " + MediaFileAPI.GetMediaFileID(mediafile) + ",'" + description + "')");
            }
    }

    public List<Object> GetGenre(Object mediafile) {
            List<Object> result = ortus.api.executeSQLQueryCache("select mediatype from allmedia where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
            if( result.size() > 0 ) {
              if ( result.get(0).equals("1") || result.equals("3"))  {
                  return ortus.api.executeSQLQueryCache("select sg.name from sage.episode as e, sage.seriesgenra as sg where e.seriesid = sg.seriesid and e.mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
              } else {
                  return ortus.api.executeSQLQueryCache("select name from sage.genre where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
              }
            } else
                return null;
    }
    
    public boolean IsTV(Object mediafile) {
	    return cacheEngine.getInstance().GetCache(mediafile).IsTV();
//            List<Object> result = ortus.api.executeSQLQuery("select mediaid from allmedia where mediatype in (1,3) and mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
//            if ( result.size() > 0)
//                return true;
//            else
//                return false;
    }

    public boolean IsRecording(Object mediafile) {
	    return cacheEngine.getInstance().GetCache(mediafile).IsRecording();
//            List<Object> result = ortus.api.executeSQLQuery("select mediaid from allmedia where mediatype in (1,3) and mediagroup = 0 and mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
//            if ( result.size() > 0)
//                return true;
//            else
//                return false;
    }


    public boolean IsMovie(Object mediafile) {
	    return cacheEngine.getInstance().GetCache(mediafile).IsMovie();
//            List<Object> result = ortus.api.executeSQLQuery("select mediaid from allmedia where mediatype = 2 and mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
//            if ( result.size() > 0)
//                return true;
//            else
//                return false;
    }

    public boolean IsHomeMovie(Object mediafile) {
            List<Object> result = ortus.api.executeSQLQueryCache("select mediaid from allmedia where mediatype = 4 and mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
            if ( result.size() > 0)
                return true;
            else
                return false;
    }

    public boolean IsSeries(Object mediafile) {
            List<Object> result = ortus.api.executeSQLQueryCache("select mediaid from allmedia where mediatype = 3 and mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
            if ( result.size() > 0)
                return true;
            else
                return false;
    }

    public boolean IsDVD(Object mediafile) {
        return MediaFileAPI.IsDVD(mediafile);
    }

    public boolean IsBluRay(Object mediafile) {
        return MediaFileAPI.IsBluRay(mediafile);
    }

    public int GetMediaType(Object mediafile) {
	    return cacheEngine.getInstance().GetCache(mediafile).GetMediaType();
//        try {
//            List<Object> result = ortus.api.executeSQLQuery("select mediatype from allmedia where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
//            if ( result.size() > 0)
//                return Integer.parseInt((String)result.get(0));
//            else
//                return 0;
//        } catch (Exception e ) {
//            ortus.api.DebugLog(TRACE2,"GetMEdiaType: Exception: " + e);
//            return 0;
//        }
    }

    public int GetSageMediaType(Object smo) {
	    return ortus.cache.cacheEngine.getInstance().GetSageMediaCache(smo).GetMediaType();
    }
    public void SetMediaType(Object mediafile, Object mediatype) {
        int workmediatype = Integer.parseInt(mediatype.toString());
        if ( GetMediaType(mediafile) == 3 && workmediatype != 3) {
            int result = ortus.api.executeSQL("update sage.episode set mediaid = null where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
        }

        int result = ortus.api.executeSQL("update sage.media set mediatype = " + workmediatype + " where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
    }

    public List<Object> GetMovies() {
            return ortus.api.getMediaFilesSQL("select mediaid from allmedia where mediatype = 2");
    }

    public List<Object> GetRecordings() {
            return ortus.api.getMediaFilesSQL("select mediaid from allmedia where mediatype = 1 and mediagroup = 1");
    }

    public List<Object> GetSeries() {
            return ortus.api.getMediaFilesSQL("SELECT mediaid FROM ALLMEDIA where mediatype = 3");
    }


    public List<Object> GetTV() {
            return ortus.api.getMediaFilesSQL("select mediaid from allmedia where mediatype = 1");
    }

    public List<Object> Search(String params) {
        return GetMediaInternal("sage.media",params);
    }

    public List<Object> GetMediaCast(String params) {
        return GetMediaInternal("allmediacast",params);
    }

    public List<Object> GetMediaGenre(String params) {
        return GetMediaInternal("allmediagenre",params);
    }

    private List<Object> GetMediaInternal(String srctable, String params) {

        if ( Ortus.getInstance().modules.get("db") == null  )
            return null;

	boolean SageMediaFormat = false;
        String sql = "select mediaid from " + srctable;
        String where = "";
        String sort = "";
        String limit = "";
        int sortcnt = 0;

        String[] p = params.split(";");
        
        for ( String x : p ) {
            ortus.api.DebugLog(TRACE2, " Processing: " + x);
            String[] work = x.split(":");
            if( work[0].equals("limit")) {
                limit = " limit " + work[1];
            }
            if ( work[0].equals("sort")) {
                String[] sp = work[1].split(",");
                for ( String y : sp ) {
                    sortcnt++;
                    if ( sort.isEmpty())
                        sort = " order by ";
                    if ( sortcnt > 1)
                        sort+=",";
                    sort+=y;
                }
            }
            if ( work[0].equals("filter")) {
                where = " where " + work[1];
            }
            if ( work[0].equals("format")) {
		    if ( work[1].equals("smo"))
			    SageMediaFormat = true;
            }

        }

        if ( ! where.isEmpty())
            sql+=where;

        if ( sortcnt > 0 )
            sql+=sort;

        if ( ! limit.isEmpty())
            sql+=limit;

        ortus.api.DebugLog(TRACE2, "GetMedia: SQL: " + sql);
	if ( SageMediaFormat)
		return ortus.api.getSageMediaFilesSQL(sql);
	else
		return ortus.api.getMediaFilesSQL(sql);
    }

	public int GetMediaGroup(Object mediafile) {
		return cacheEngine.getInstance().GetCache(mediafile).GetMediaGroup();
//            List<Object> result = ortus.api.executeSQLQuery("select mediagroup from sage.media where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
//            if ( result.size() > 0)
//                return Integer.parseInt((String)result.get(0));
//            else
//                return 0;
        }

	public int GetSageMediaGroup(Object smo) {
		return ortus.cache.cacheEngine.getInstance().GetSageMediaCache(smo).GetMediaGroup();
	}
	public boolean IsTVMovie(Object mediafile) {
            return false;
        }
	public boolean IsImportedTV(Object mediafile) {
            return false;
        }
	public boolean IsRecorded(Object mediafile) {
            return false;
        }
	public boolean IsImported(Object mediafile) {
            return false;
        }
	public boolean IsIntelligentRecorded(Object mediafile) {
            return false;
        }

	public boolean IsFavorite(Object mediafile) {
            return false;
        }
	public boolean IsHD(Object mediafile) {
            return false;
        }
	public boolean IsSD(Object mediafile) {
            return false;
        }
	public boolean IsHDMovie(Object mediafile) {
            return false;
        }
	public boolean IsSDMovie(Object mediafile) {
            return false;
        }

	//Common Metadata
	public String GetMediaFileID(Object mediafile) {
            return String.valueOf(MediaFileAPI.GetMediaFileID(mediafile));
        }
	public String GetImportDate(Object mediafile) {
            List<Object> result = ortus.api.executeSQLQueryCache("select mediaimporttime from sage.media where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
            if ( result.size() > 0)
                return (String)result.get(0);
            else
                return null;
        }
	public String GetPath(Object mediafile) {
		return cacheEngine.getInstance().GetCache(mediafile).GetMediaPath();
//            List<Object> result = ortus.api.executeSQLQuery("select mediapath from sage.media where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
//            if ( result.size() > 0)
//                return (String)result.get(0);
//            else
//                return null;
//
        }
	public String GetMediaEncoding(Object mediafile) {
		return cacheEngine.getInstance().GetCache(mediafile).GetMediaEncoding();
//            List<Object> result = ortus.api.executeSQLQuery("select mediaencoding from sage.media where mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
//            if ( result.size() > 0)
//                return (String)result.get(0);
//            else
//                return null;
        }
	public String GetVideoEncoding(Object mediafile) {
            return null;
        }
	public String GetAudioEncoding(Object mediafile) {
            return null;
        }
	public String GetSubpicEncoding(Object mediafile) {
            return null;
        }

	//TV Series Metadata
	public String GetSeriesTitle(Object mediafile) {
            return null;
        }
	public String GetSeriesDescription(Object mediafile) {
            return null;
        }
	public String GetSeriesNetwork(Object mediafile) {
            List<Object> result = ortus.api.executeSQLQueryCache("select s.network from sage.series as s, sage.episode as e where s.seriesid = e.seriesid and e.mediaid = " + MediaFileAPI.GetMediaFileID(mediafile));
            return (String)result.get(0);            
        }
	public long GetSeriesFirstAirDate(Object mediafile) {
            return 0;
        }
	public long GetSeriesFinalAirDate(Object mediafile) {
            return 0;
        }
	public boolean IsSeriesStillRunning(Object mediafile) {
            return false;
        }
	public String GetSeriesAirDay(Object mediafile) {
            return null;
        }
	public long GetSeriesRunTime(Object mediafile) {
            return 0;
        }
	public long GetSeriesNextEpisodeDate(Object mediafile) {
            return 0;
        }
	public String GetSeriesTVRating(Object mediafile) {
            return null;
        }
	public int GetSeriesTotalSeasons(Object mediafile) {
            return 0;
        }
	public int GetSeriesTotalEpisodes(Object mediafile) {
            return 0;
        }
	public int GetSeriesTotalEpisodesAvailable(Object mediafile) {
            return 0;
        }

	//TV Metadata

	//Movie Metadata
	//Cast Metadata
    public String GetDirector(Object mediafile) {
        return null;
    }
    public String GetWriter(Object mediafile) {
        return null;
    }
    public String GetProducer(Object mediafile) {
        return null;
    }
    public List<String> GetActors(Object mediafile) {
        return null;
    }

    public List<String> GetCast(Object mediafile) {
        return null;
    }
    public String GetMPAARating(Object mediafile) {
        return cacheEngine.getInstance().GetCache(mediafile).GetMPAARated();
    }
    public String GetSageMPAARating(Object smo) {
	    return ortus.cache.cacheEngine.getInstance().GetSageMediaCache(smo).GetMPAARated();
    }
    public int GetUserRating(Object mediafile) {
	    return Math.round(cacheEngine.getInstance().GetCache(mediafile).GetUserRating());
    }
    public int GetSageUserRating(Object smo) {
	    return Math.round(ortus.cache.cacheEngine.getInstance().GetSageMediaCache(smo).GetUserRating());
    }
    public int GetDiscNumber(Object mediafile) {
        return 0;
    }
    public String GetReleaseDate(Object mediafile) {
        return null;
    }

}
